<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import styles from './shopping.module.css'

const router = useRouter()
const productList = ref<any[]>([])
const loading = ref(false)
const sortKey = ref('default')
const sortOptions = [
  { label: '默认排序', value: 'default' },
  { label: '价格升序', value: 'price_asc' },
  { label: '价格降序', value: 'price_desc' },
  { label: '销量最高', value: 'sold_desc' }
]

const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:3000/YJL/waterlist', { params: { page: 1, pageSize: 1000 } })
    productList.value = res.data.data
  } finally {
    loading.value = false
  }
}

const sortedProducts = computed(() => {
  let arr = [...productList.value]
  if (sortKey.value === 'price_asc') arr.sort((a, b) => a.price - b.price)
  else if (sortKey.value === 'price_desc') arr.sort((a, b) => b.price - a.price)
  else if (sortKey.value === 'sold_desc') arr.sort((a, b) => (b.sold || 0) - (a.sold || 0))
  return arr
})

function goSearch() {
  router.push('/search')
}

onMounted(() => {
  fetchProducts()
})
</script>
<template>
  <div :class="styles.shoppingPage">
    <!-- 搜索头部栏 -->
    <div :class="styles.searchBar">
      <input :class="styles.searchInput" placeholder="🔍 搜索商品" readonly @click="goSearch" />
    </div>
    <!-- 排序栏 -->
    <div :class="styles.sortBar">
      <span v-for="opt in sortOptions" :key="opt.value" :class="[styles.sortBtn, sortKey === opt.value ? styles.active : '']" @click="sortKey = opt.value">
        {{ opt.label }}
      </span>
    </div>
    <!-- 商品列表 -->
    <div :class="styles.productGrid">
      <div v-for="item in sortedProducts" :key="item._id" :class="styles.productCard">
        <img :src="item.images" :alt="item.name" :class="styles.productImg" />
        <div :class="styles.productTitle">{{ item.name }}</div>
        <div :class="styles.productPrice">¥{{ item.price }}</div>
      </div>
    </div>
    <div v-if="loading" :class="styles.loadingText">加载中...</div>
  </div>
</template>
